package class03;

import utils.ArrayUtil;

import java.util.Arrays;

/**
 * @ClassName BSNearLeft  有序数组中找 大于等于 num的最左位置
 * @Description:
 * @Author: WangWenpeng
 * @date: 6:47 2021/5/24
 * @Version 1.0
 */
public class Code02_BSNearLeft {

    //有序数组中找大于等于num的最左侧的位置     有序递增数组  二分法递归
    public static int mostLeftNoLessNumIndex(int[] arr, int num) {
        if (arr == null || arr.length == 0) {
            return -1;
        }
        int L = 0, R = arr.length - 1, ans = -1;
        while (L <= R) {
            int mid = (L + R) / 2;
            if (arr[mid] >= num) {
                ans = mid;
                R = mid - 1;
            } else {
                L = mid + 1;
            }
        }
        return ans;
    }

    //大于等于num的最左侧的位置
    public static int violenceForSearch(int[] arr, int num) {
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] >= num) {
                return i;
            }
        }
        return -1;
    }

    /**
     * 测试方法
     *
     * @param args
     */
    public static void main(String[] args) {
        int testTime = 500000;
        int maxSize = 10;
        int maxValue = 100;
        boolean succeed = true;

        for (int i = 0; i < testTime; i++) {
            int[] arr = ArrayUtil.generateRandomArray(maxSize, maxValue,true,false);
            Arrays.sort(arr);

            int value = (int) ((maxValue + 1) * Math.random()) - (int) (maxValue * Math.random());
            if (violenceForSearch(arr, value) != mostLeftNoLessNumIndex(arr, value)) {
                ArrayUtil.printArray(arr);
                System.out.println(value);
                System.out.println(violenceForSearch(arr, value));
                System.out.println(mostLeftNoLessNumIndex(arr, value));
                succeed = false;
                break;
            }
        }
        System.out.println(succeed ? "Nice!" : "Fucking fucked!");
    }
}
